package com.code.commons.web.interceptor;

import com.code.commons.util.StringUtil;
import com.code.commons.web.constants.HeaderConstants;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 允许跨域拦截器
 * <p>跨域拦截器相关的bean，针对线上环境最好使用nginx进行代理中转，开发与测试使用CORS即可，对于使用jsoup，
 * 由于jsoup只能支持GET方法的请求，我看到一些公司为了支持JSONP将后端的添加、修改、删除功能接口都改为GET方式，
 * 这种是很不建议的，这样会存在安全隐患。如果你用的是spring boot的话可以参考下AbstractJsonpResponseBodyAdvice这个类的使用。</p>
 *
 * @author tangyifei
 * @since 2019-5-24 10:58:40
 */
public class AllowCrossDomainInterceptor implements HandlerInterceptor {

  /*  @Autowired
    private Environment env;*/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

       /* if (!EnvironmentEnum.isProdEnv(env)) {*/
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", StringUtil.isEmpty(origin) ? "*" : origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
        response.setHeader("Access-Control-Max-Age", "0");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache," +
                " X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,"
                + HeaderConstants.X_TOKEN + "," + HeaderConstants.CALL_SOURCE + "," + HeaderConstants.API_VERSION + ","
                + HeaderConstants.APP_VERSION + "," + HeaderConstants.LANGUAGE);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("XDomainRequestAllowed", "1");
       /* }*/

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // nothing to do
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // nothing to do
    }

}
